package Sort;

import java.util.Arrays;

/**
 * @Author: 吕庆龙
 * @Date: 2019/10/1 17:40
 * <p>
 * 功能描述: 归并算法
 */
public class MergeSort {
    public static void main(String[] args) {
        int arr[] = {8, 4, 5, 7, 1, 3, 6, 2};
        int temp[] = new int[arr.length];
        mergeSort(arr, 0, arr.length - 1, temp);
        System.out.println("归并排序后=" + Arrays.toString(arr));
    }

    /**
     * 功能描述:分+治
     */
    public static void mergeSort(int[] a, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            //从左递归
            mergeSort(a, left, mid, temp);
            //从右递归
            mergeSort(a, mid + 1, right, temp);
            //治
            merge(a, left, mid, right, temp);
        }
    }

    public static void merge(int[] a, int left, int mid, int right, int[] temp) {
        int i = left;int j = mid + 1;int t = 0;
        //1.治
        while (i <= mid && j <= right) {
            if (a[i] <= a[j]) {
                temp[t] = a[i];
                i++;
                t++;
            } else {
                temp[t] = a[j];
                j++;
                t++;
            }
        }
        //2.多的直接放到temp数组
        while (i <= mid) {  //注意这里是while不是if
            temp[t] = a[i];
            i++;
            t++;
        }
        while (j <= right) {
            temp[t] = a[j];
            j++;
            t++;
        }
        //3.拷贝temp数组
        int templeft = left;
        t = 0;
        while (templeft <= right) {
            a[templeft] = temp[t];
            templeft++;
            t++;
        }
    }
}
